import type { PermissionInfo, PermissionQuery, PermissionTreeNode, MenuTreeNode } from '@/types/permission.type'
import type { ApiResponse, PageResult } from '@/types/common.type'
import request from '@/utils/request'

// 获取权限列表
export function getPermissionList(params: PermissionQuery): Promise<ApiResponse<PageResult<PermissionInfo>>> {
  return request({
    url: '/api/system/permissions/page',
    method: 'get',
    params
  })
}

// 获取权限树
export function getPermissionTree(): Promise<PermissionTreeNode[]> {
  return request({
    url: '/api/system/roles/permissions/tree',
    method: 'get'
  })
}

// 获取菜单树
export function getMenuTree(): Promise<ApiResponse<MenuTreeNode[]>> {
  return request({
    url: '/api/system/permissions/tree',
    method: 'get'
  })
}

// 创建权限
export function createPermission(data: Omit<PermissionInfo, 'id'>): Promise<ApiResponse<number>> {
  return request({
    url: '/api/system/permissions',
    method: 'post',
    data
  })
}

// 更新权限
export function updatePermission(data: PermissionInfo): Promise<ApiResponse<void>> {
  return request({
    url: '/api/system/permissions',
    method: 'put',
    data
  })
}

// 删除权限
export function deletePermission(id: number): Promise<ApiResponse<void>> {
  return request({
    url: `/api/system/permissions/${id}`,
    method: 'delete'
  })
}

// 分配权限
export function assignPermissions(data: { roleId: number; permissionIds: number[] }) {
  return request({
    url: `/api/system/roles/assign-permissions`,
    method: 'POST',
    data: { roleId:data.roleId,permissionIds: data.permissionIds }
  })
}

/**
 * 获取指定角色的权限ID列表
 * @param roleId 角色ID
 */
export function getRolePermissions(roleId: number) {
  return request({
    url: `/api/system/roles/permissions/${roleId}`,
    method: 'get'
  })
}

// 获取当前用户权限树
export const getCurrentUserPermissionTree = () => {
  console.log('开始调用获取当前用户权限树接口')
  return request.get<PermissionInfo[]>('/api/system/permissions/current/tree')
    .then(data => {
      console.log('权限树接口返回数据:', data)
      if (Array.isArray(data)) {
        console.log('权限树数据结构:', {
          hasData: true,
          isArray: true,
          dataLength: data.length,
          firstItem: data[0]
        })
      } else {
        console.warn('权限树数据不是数组:', data)
      }
      return data
    })
    .catch(error => {
      console.error('获取权限树失败:', error)
      throw error
    })
} 